<template>
	<view class="container bg-main pos-r">
		<use-navbar title="登录"></use-navbar>

		<view class="padding-xl dflex-c dflex-flow-c">
			<view class="headimg-box margin-top-big margin-bottom-xs">
				<image class="headimg border-radius-c" :src="'/static/images/logo.png'"></image>
			</view>

			<view class="fs-xxl fwbd line-height-1">{{ config.appname }}</view>
			<view class="margin-top-sm ft-dark-4">{{ config.appslogan }}</view>

			<button class="dflex-c dflex-flow-c no-border btn margin-top-big padding-top" lang="zh_CN" @click="mpWeixinTologin">
				<view class="dflex-c fs border-radius-big"
					style="background-color: #28c445; color: #fff; padding: 20rpx 150rpx;">一键快捷登录</view>
			</button>
		</view>

		<!-- 绑定手机号 -->
		<use-popup v-model="bindMobileShow" bgclass=" " mode="top" @close="bindMobileShow = false;">
			<view class="bind-area bg-main pos-r border-radius-bottom">

				<!-- #ifdef MP-WEIXIN -->
				<view class="dflex margin-lr">
					<view class="dflex-c">
						<image class="headimg border-radius" style="width: 100rpx;height: 100rpx;"
							src="/static/images/logo.png"></image>
					</view>
					<view class="margin-left-sm">
						<view class="fwbd fs">{{ config.appname }}</view>
						<view class="dflex fs-xs">
							<view>申请授权获取你的手机号</view>
						</view>
					</view>
				</view>

				<view class="dflex-c dflex-flow-c" style="padding: 120rpx 0;">
					<image class="headimg border-radius-c" style="width: 80rpx;height: 80rpx;"
						:src="(member && member.member_headimg) || '/static/images/user/default.png'"></image>
					<view class="fwb">{{ member && member.member_nickname || 'Usecloud' }}</view>
				</view>

				<!-- 微信手机号一键绑定并登录 -->
				<button class="btn no-border padding-0" open-type="getPhoneNumber" @getphonenumber="mpPhoneNumber"
					@click="islogin = true">
					<view class="w-full margin-top-xxl padding-bottom-xl">
						<view class="dflex-b border-radius-lg">
							<view class="dflex-c padding-tb-sm flex1 bg-base fs">
								<view v-if="islogin" class="use-loading margin-right-sm"></view>
								绑定并登录
							</view>
						</view>
					</view>
				</button>
				<!-- #endif -->
			</view>
		</use-popup>

		<!-- 完善头像、昵称数据 -->
		<use-popup v-model="bindPerfectShow" bgclass=" " mode="top" @close="bindPerfectShow = false;">
			<view class="bind-area bg-main pos-r border-radius-bottom">
				<!-- #ifdef MP-WEIXIN -->
				<view class="dflex margin-lr">
					<view class="dflex-c">
						<image class="headimg border-radius" style="width: 100rpx;height: 100rpx;"
							src="/static/images/logo.png"></image>
					</view>
					<view class="margin-left-sm">
						<view class="fwbd fs">{{ config.appname }}</view>
						<view class="dflex fs-xs">
							<view>请完善您的头像、昵称数据</view>
						</view>
					</view>
				</view>

				<form @submit="toUpdateUser">
					<view class="dflex-c dflex-flow-c" style="padding: 120rpx 0;">
						<view class="dflex-b w-full">
							<view class="margin-right dflex-c"><text style="color: #ff6a6c;"
									class="padding-lr-xs">*</text>头像</view>
							<button class="btn no-border padding-0 fs-sm ft-dark" style="margin: 0;"
								open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
								<view v-if="!avatarUrl" class="headimg border-radius-c dflex-c"
									style="width: 130rpx;height: 130rpx;">
									<view class="iconfont iconhaibao" style="font-size: 58rpx;"></view>
								</view>
								<image v-else class="headimg border-radius-c dflex-c"
									style="width: 130rpx;height: 130rpx;" mode="aspectFit" :src="avatarUrl"></image>
							</button>
						</view>

						<view class="dflex-b w-full margin-top">
							<view class="margin-right dflex-c"><text style="color: #ff6a6c;"
									class="padding-lr-xs">*</text>昵称</view>
							<view class="flex1 bg-drak border-radius">
								<input name="nickname" type="nickname" class="w-full padding-left"
									style="height: 90rpx;" placeholder="请输入昵称" />
							</view>
						</view>
					</view>

					<!-- 保存并登录 -->
					<button class="btn no-border" form-type="submit">
						<view class="w-full margin-top-xxl padding-bottom-xl">
							<view class="dflex-b border-radius-lg">
								<view class="dflex-c padding-tb-sm flex1 bg-base fs">
									<view v-if="isubmit" class="use-loading margin-right-sm"></view>
									保存并登录
								</view>
							</view>
						</view>
					</button>
				</form>
				<!-- #endif -->
			</view>
		</use-popup>

		<!-- 隐私保护指引 -->
		<use-popup v-model="privacyShow" bgclass=" " mode="bottom" :maskCloseAble="false">
			<view class="padding-xl bg-main pos-r border-radius-top30">
				<view class="dflex">
					<view class="dflex-c">
						<image class="headimg border-radius" style="width: 100rpx;height: 100rpx;"
							src="/static/images/logo.png"></image>
					</view>
					<view class="margin-left-sm">
						<view class="fwbd fs">{{ config.appname }}</view>
						<view class="dflex fs-xs">
							<view>小程序隐私保护指引</view>
						</view>
					</view>
				</view>
				
				<view class="margin-top">在您使用小程序之前，请仔细阅读<text class="ft-base2" @click="openPrivacyContract">《{{ config.appname }}小程序隐私保护指引》</text>。如您点击同意即代表已理解并同意隐私保护内容。如您拒绝将无法正常为您提供在线购物服务。</view>
				
				<view class="dflex-e margin-top-xl">
					<view class="bg-drak border-radius-big padding-16 padding-lr-xl" @click="privacyShow = false">拒绝</view>
					<button class="no-border btn-normal" open-type="agreePrivacyAuthorization" @agreeprivacyauthorization="toAgreePrivacyAuthorization">
						<view class="bg-base border-radius-big padding-16 padding-lr-xl margin-left">同意</view>
					</button>
				</view>
				
				<view class="w-full safe-area-inset-bottom"></view>
			</view>
		</use-popup>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';

	export default {
		data() {
			return {
				agreement: true,
				privacyShow: false,

				avatarUrl: '',
				bindMobileShow: false,
				bindPerfectShow: false,

				isubmit: 0,
				userPerfect: {
					is_perfect: 1,
					avatar: '',
					nickname: ''
				},
				loginRes: {}
			};
		},
		computed: {
			...mapState(['member']),
			config() {
				return this.$config;
			}
		},

		onShow() {},
		onLoad() {
			// #ifdef MP-WEIXIN
			uni.getPrivacySetting({
				success: res => {
					console.log('getPrivacySetting', res);
					if (res.needAuthorization) {
						this.agreement = false;
						this.privacyShow = true;
					}
				},
				fail: err => {
					console.log('getPrivacySetting err', err);
				}
			});
			// #endif
		},
		methods: {
			...mapMutations(['login', 'logout', 'token']),
			// 选择头像
			async onChooseAvatar(res) {
				// console.log('onChooseAvatar', res);
				this.avatarUrl = res.detail.avatarUrl;
				uni.showLoading({
					title: '上传中'
				});

				// 上传图片
				const uRes = await this.$api.uploadFile(this.avatarUrl, `${Date.now()}.png`)
					.catch(err => {
						this.$api.msg(err.message);
						uni.hideLoading();
					});
				
				uni.hideLoading();
				this.userPerfect.avatar = uRes.url;
			},
			toUpdateUser(res) {
				// console.log('toUpdateUser', res);

				if (!this.userPerfect.avatar) {
					this.$api.msg('请选择头像');
					return;
				}

				this.userPerfect.nickname = res.detail.value.nickname;
				if (!this.userPerfect.nickname) {
					this.$api.msg('请填写昵称');
					return;
				}

				// 用户 Token
				const token = this.loginRes.user.token;

				this.isubmit = 1;
				this.$func.usemall.call('member/updateUser', {
					token,
					...this.userPerfect
				}).then(res => {
					this.isubmit = 0;
					console.log('member/updateUser', res);

					if (res.code == 200) {
						this.bindPerfectShow = false;

						this.loginRes.member.member_headimg = this.userPerfect.avatar;
						this.loginRes.member.member_nickname = this.userPerfect.nickname;
						this.loginRes.member.is_perfect = 1;

						this.loginCommon(this.loginRes);
						return;
					}

					this.$api.msg(res.msg);
				});
			},
			loginCommon(res) {
				this.loginRes = res;

				if (res.member && res.member.is_perfect !== 1) {
					// 完善用户头像、昵称数据
					this.bindPerfectShow = true;

					if (this.bindMobileShow) this.bindMobileShow = false;
					return;
				}

				if (res.member && res.member.is_plus === '付费会员' && res.member.plus_time >= Date.now()) {
					res.member.vip = true;
				}

				// 调用 store login
				this.login(res);

				// 存储已授权登录
				uni.setStorageSync('__usemall_login', this.$api.format(new Date(), 'yyyyqq'));

				this.$api.msg('登录成功');
				this.$api.back();
			},

			// #ifdef MP-WEIXIN || APP
			openPrivacyContract() {
				// 打开隐私协议页面
				uni.openPrivacyContract({
					success: () => { },
					fail: () => { }
				});
			},
			toAgreePrivacyAuthorization() {
				this.agreement = true;
				this.privacyShow = false;
			},
			mpWeixinTologin() {
				
				if (!this.agreement) {
					this.privacyShow = true;
					return;
				}

				uni.showLoading({
					title: '处理中'
				});

				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success: (mpres) => {
						console.log('uni.login', mpres);
						if (mpres.errMsg == 'login:ok') {
							this.$func.usemall
								.call('member/loginByWeixin', {
									sharemid: uni.getStorageSync('__use_share_mid') || '',
									code: mpres.code
								})
								.then(res => {
									if (res.code == 100) {
										// 已登录用户ID
										const userRes = {
											uid: res.result.datas
										};
										uni.setStorage({
											key: '__wxuser',
											data: userRes
										})
										// 未绑定手机号
										this.bindMobileShow = true;
										this.$api.msg(res.msg);
										return;
									}

									if (res.code == 200) {
										console.log('member/loginByWeixin', res);

										this.loginCommon(res.datas);
										return;
									}

									this.$api.msg(res.msg);
								})
								.catch(err => {
									this.$api.alert(err.message);
								})
								.finally(() => {
									uni.hideLoading();
								});
						}
					},
					fail: (err) => {
						console.log('uni.login', err);
						uni.hideLoading();
					}
				});
			},
			async getWeixinCode() {
				return new Promise((resolve, reject) => {
					// #ifdef MP-WEIXIN
					uni.login({
						success: (res) => {
							resolve(res.code);
						},
						fail: (err) => {
							reject(err)
						}
					});
					// #endif
					// #ifdef APP
					weixinAuthService.authorize((res) => {
						resolve(res.code)
					}, (err) => {
						console.log(err)
						reject(new Error('微信登录失败'))
					});
					// #endif
				})
			},
			// #endif
			// #ifdef MP-WEIXIN
			// 微信小程序手机号
			async mpPhoneNumber(res) {

				if (!(res.detail && res.detail.encryptedData)) {
					this.islogin = false;
					if (res.detail.errMsg === 'getPhoneNumber:fail no permission' && this.platform === 'qq') {
						uni.showToast({
							title: 'QQ暂无法获取手机号',
							icon: 'none'
						});
					} else {
						// uni.showToast({
						// 	title: '您取消了授权',
						// 	icon: 'none'
						// });
					}

					// uni.navigateBack();
					return false;
				}
				console.log('用户授权', res.detail);

				uni.showLoading({
					title: '处理中'
				});

				const wxcode = await this.getWeixinCode();

				this.$func.usemall
					.call('member/loginByPhoneNumber', {
						sharemid: uni.getStorageSync('__use_share_mid') || '',
						user: uni.getStorageSync('__wxuser') || {},
						wxcode: wxcode,
						...res.detail
					})
					.then(res => {
						this.islogin = false;
						uni.hideLoading();

						if (res.code == 60101 || [103, 104].includes(res.code)) {
							this.$api.alert(res.msg);
							this.bindMobileShow = false;
							return;
						}

						if (res.code == 200) {
							console.log('member/loginByPhoneNumber', res);

							this.loginCommon(res.datas);
							return;
						}

						this.$api.msg(res.msg);
					});
			},
			// #endif
		}
	};
</script>

<style lang="scss">
	.headimg-box {
		image {
			width: 168rpx;
			height: 168rpx;
		}
	}

	.bind-area {
		width: 100vw;
		padding: 80rpx;
		padding-top: 100rpx;

		.field {
			background-color: #f5f5f5;

			textarea {
				height: 100rpx !important;
			}
		}
	}
</style>